﻿using System;
using System.IO;
using System.IO.IsolatedStorage;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace Silverlight.Navigation.Favorites
{
    public class IsolatedStorageFavoritesManager : FavoritesManager
    {
        #region Constructors

        /// <summary>
        /// Initilaizes a new instance of the IsolatedStorageFavoritesManager class.
        /// </summary>
        /// <param name="key">The key used by isolated storage for saving and retrieval.</param>
        public IsolatedStorageFavoritesManager(string key)
        {
            if (string.IsNullOrEmpty(key))
                throw new ArgumentNullException("key");

            Key = key;
        }

        #endregion

        #region Properties

        /// <summary>
        /// The user specified home page.
        /// </summary>
        public override FavoriteItem HomePage
        {
            get
            {
                if (IsolatedStorageSettings.ApplicationSettings.Contains(Key + ".HomePage"))
                {
                    if (IsolatedStorageSettings.ApplicationSettings[Key + ".HomePage"] != null &&
                        IsolatedStorageSettings.ApplicationSettings[Key + ".HomePage"] is FavoriteItem)
                    {
                        return (FavoriteItem)IsolatedStorageSettings.ApplicationSettings[Key + ".HomePage"];
                    }
                    else
                        return null;
                }
                else
                    return null;
            }
            set
            {
                IsolatedStorageSettings.ApplicationSettings[Key + ".HomePage"] = value;
            }
        }

        /// <summary>
        /// The key used by isolated storage for saving and retrieval.
        /// </summary>
        public string Key { get; set; }

        #endregion

        #region Methods

        /// <summary>
        /// Loads the favorite items.
        /// </summary>
        public override void Load()
        {
            if (IsolatedStorageSettings.ApplicationSettings.Contains(Key))
                this.FavoriteItems = (FavoriteItemCollection)IsolatedStorageSettings.ApplicationSettings[Key];
            else
                this.FavoriteItems = new FavoriteItemCollection();
        }

        /// <summary>
        /// Saves the favorite items.
        /// </summary>
        public override void Save()
        {
            IsolatedStorageSettings.ApplicationSettings[Key] = this.FavoriteItems;
        }

        #endregion
    }
}
